package com.aliyun.sms.sdk;

import com.alibaba.fastjson.JSON;
import com.aliyun.sms.sdk.config.AliyunProperties;
import com.aliyun.sms.sdk.domain.NoticeData;
import com.aliyun.sms.sdk.domain.QuerySendDetailData;
import com.aliyun.sms.sdk.domain.SendBatchSmsData;
import com.aliyun.sms.sdk.handler.SendHandler;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.*;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;


/**
 * @Author： yu.Tan
 * @Date: 2021/1/12 16:12
 * @Description:
 */
@Slf4j
public class AliyunSendHandler implements SendHandler {

    private static final String OK = "OK";

    private static final String PRODUCT = "Dysmsapi";

    private static final String DOMAIN = "dysmsapi.aliyuncs.com";

    @Autowired
    private AliyunProperties properties;

    @Autowired
    private  ObjectMapper objectMapper;

    @Autowired
    private  IAcsClient acsClient;


    /**
     * 构造阿里云短信发送处理
     * @param properties  阿里云短信配置
     * @param objectMapper
     */
    public AliyunSendHandler(AliyunProperties properties, ObjectMapper objectMapper) {
        this.properties = properties;
        this.objectMapper = objectMapper;
        String endPoint = properties.getEndpoint();
        String accessKeyId = properties.getAccessKeyId();
        String accessKeySecret = properties.getAccessKeySecret();

        IClientProfile profile = DefaultProfile.getProfile(endPoint, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(endPoint, PRODUCT, DOMAIN);

        acsClient = new DefaultAcsClient(profile);
    }



    public SendSmsResponse send(NoticeData noticeData, Collection<String> phones) {
        String paramString;
        try {
            paramString = objectMapper.writeValueAsString(noticeData.getParams());
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
            return null;
        }

        SendSmsRequest request = new SendSmsRequest();
        request.setSysMethod(MethodType.POST);
        request.setPhoneNumbers(StringUtils.join(phones, ","));
        request.setSignName(properties.getSignName());
        request.setTemplateCode(properties.getTemplates(noticeData.getType()));
        request.setTemplateParam(paramString);

        try {
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

            if (OK.equals(sendSmsResponse.getCode())) {
                return sendSmsResponse;
            }

            log.info("send fail[code={}, message={}]", sendSmsResponse.getCode(), sendSmsResponse.getMessage());
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
        return null;
    }

    public SendSmsResponse send(NoticeData noticeData, String phone) {
        if (StringUtils.isEmpty(phone)) {
            return null;
        }

        return send(noticeData, Collections.singletonList(phone));
    }

    public SendSmsResponse send(NoticeData noticeData, String... phones) {
        if (phones == null) {
            return null;
        }

        return send(noticeData, Arrays.asList(phones));
    }

    public SendBatchSmsResponse sendBatch(SendBatchSmsData sendBatchSmsData) {

        List<String> phoneNumbers = sendBatchSmsData.getPhoneNumbers();

        List<String> templateParam = sendBatchSmsData.getTemplateParams();
        List<String> signNames = sendBatchSmsData.getSignNames();


        String phoneNumberJson = JSON.toJSONString(phoneNumbers.toArray());
        String templateParamJson = JSON.toJSONString(templateParam.toArray());
        String signNameJson = JSON.toJSONString(signNames.toArray());


        SendBatchSmsRequest request=new SendBatchSmsRequest();
        request.setSysMethod(MethodType.POST);
        request.setSignNameJson(signNameJson);
        request.setTemplateCode(properties.getTemplates(sendBatchSmsData.getType()));
        request.setPhoneNumberJson(phoneNumberJson);
        request.setTemplateParamJson(templateParamJson);


        try {
            SendBatchSmsResponse sendBatchSmsResponse = acsClient.getAcsResponse(request);

            if (OK.equals(sendBatchSmsResponse.getCode())) {
                return sendBatchSmsResponse;
            }
            log.info("send fail[code={}, message={}]", sendBatchSmsResponse.getCode(), sendBatchSmsResponse.getMessage());
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
        return null;
    }

    public QuerySendDetailsResponse querySendDetails(QuerySendDetailData querySendDetailData) {

        QuerySendDetailsRequest request=new QuerySendDetailsRequest();
        request.setSysMethod(MethodType.POST);
        request.setPhoneNumber(querySendDetailData.getPhoneNumber());
        request.setPageSize(querySendDetailData.getPageSize());
        request.setCurrentPage(querySendDetailData.getCurrentPage());
        request.setBizId(querySendDetailData.getBizId());

        try {
            QuerySendDetailsResponse acsResponse = acsClient.getAcsResponse(request);

            if (OK.equals(acsResponse.getCode())) {
                return acsResponse;
            }
            log.info("send fail[code={}, message={}]", acsResponse.getCode(), acsResponse.getMessage());
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
        return null;
    }

}
